package com.uml.youmath;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.TextView;

public class ScoreScreen extends Activity implements OnClickListener{
	Button button1;
	ArrayList<TextView> names;
	ArrayList<TextView> scores;
	TextView swishLabel;
	TextView swishMiniLabel;
	int reportedScore = 0;
	String username;
	int stageSelect = 0;
	RadioButton scoreEasy, scoreMedium, scoreHard, scoreExpert;
	RadioGroup radGrp;
	int currentPos = 0;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.scorescreen);
	    // TODO Auto-generated method stub
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		username = prefs.getString(getResources().getString(
				R.string.username_pref), getResources().getString(
				R.string.username_pref_default));
		button1 = (Button) findViewById(R.id.button1);
		scoreEasy = (RadioButton) findViewById(R.id.scoreEasy);
		scoreMedium = (RadioButton) findViewById(R.id.scoreMedium);
		scoreHard = (RadioButton) findViewById(R.id.scoreHard);
		scoreExpert = (RadioButton) findViewById(R.id.scoreExpert);
		radGrp = (RadioGroup) findViewById(R.id.radioGroup1);
		scoreEasy.setOnClickListener(this);
		scoreMedium.setOnClickListener(this);
		scoreHard.setOnClickListener(this);
		scoreExpert.setOnClickListener(this);
		button1.setOnClickListener(this);
		
	    Bundle extras = getIntent().getExtras();
	    reportedScore = extras.getInt("Score");
	    stageSelect = extras.getInt("stageSelect");
	    names = new ArrayList(10);
	    scores = new ArrayList(10);
	    names.add((TextView) this.findViewById(R.id.Name0));
	    names.add((TextView) this.findViewById(R.id.Name1));
	    names.add((TextView) this.findViewById(R.id.Name2));
	    names.add((TextView) this.findViewById(R.id.Name3));
	    names.add((TextView) this.findViewById(R.id.Name4));
	    names.add((TextView) this.findViewById(R.id.Name5));
	    names.add((TextView) this.findViewById(R.id.Name6));
	    names.add((TextView) this.findViewById(R.id.Name7));
	    scores.add((TextView) this.findViewById(R.id.Score0));
	    scores.add((TextView) this.findViewById(R.id.Score1));
	    scores.add((TextView) this.findViewById(R.id.Score2));
	    scores.add((TextView) this.findViewById(R.id.Score3));
	    scores.add((TextView) this.findViewById(R.id.Score4));
	    scores.add((TextView) this.findViewById(R.id.Score5));
	    scores.add((TextView) this.findViewById(R.id.Score6));
	    scores.add((TextView) this.findViewById(R.id.Score7));
	    swishLabel = (TextView) this.findViewById(R.id.swishLabel);
	    swishLabel.setText("You scored " + reportedScore + "!");
	    //swishMiniLabel = (TextView) this.findViewById(R.id.textView1);
	    
	    populateScores(stageSelect);
	    if (reportedScore == -1 && stageSelect == -1) {
	    	swishLabel.setText("SCOREBOARD");
	    	button1.setVisibility(View.INVISIBLE);
	    	//swishMiniLabel.setVisibility(View.INVISIBLE);
	    } else {
	    	radGrp.setVisibility(View.GONE);
	    	radGrp.setVisibility(View.GONE);
	    	scoreEasy.setVisibility(View.GONE);
	    	scoreMedium.setVisibility(View.GONE);
	    	scoreHard.setVisibility(View.GONE);
	    	scoreExpert.setVisibility(View.GONE);
	    }
	}

	public void populateScores(int scoreType) {
		int i;
		JSONObject jObject;
		try {
			String diff = "easy";
			switch(scoreType) {
			case 0: 
				diff = "easy";
				break;
			case 1:
				diff = "medium";
				break;
			case 2:
				diff = "hard";
				break;
			case 3:
				diff = "expert";
				break;
			}
	        HttpClient client = new DefaultHttpClient();  
	        String getURL = "http://www.reedmagic.com/android/highscores.php?limit=6&difficulty=" + diff;
	        HttpGet get = new HttpGet(getURL);
	        HttpResponse responseGet = client.execute(get);  
	        HttpEntity resEntityGet = responseGet.getEntity();  
	        if (resEntityGet != null) {  
	                    //do something with the response
	        			JSONArray jArray = new JSONArray(EntityUtils.toString(resEntityGet));
	        			for (i = 0; i < jArray.length() && i < 7; i++) {
	        				jObject = new JSONObject(jArray.get(i).toString());
	        				names.get(i).setText(jObject.get("name").toString().trim());
	        				scores.get(i).setText(jObject.get("score").toString().trim());
	        			}
	        			for ( ; i <= 7; i++ ) {
	        				names.get(i).setText("Future Winner");
	        				scores.get(i).setText("0");
	        			}
	                    //scores.get(0).setText(EntityUtils.toString(resEntityGet));
	                }
		} catch (Exception e) {
			e.printStackTrace();
			scores.get(0).setText(e.toString());
		}

 	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
			 Intent i = new Intent(ScoreScreen.this, YouMath.class);
			 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
			 i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			 startActivity(i);
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onClick(View v) {
	try{
		String diff = "easy";
		
		switch(stageSelect) {
		case 0: 
			diff = "easy";
			break;
		case 1:
			diff = "medium";
			break;
		case 2:
			diff = "hard";
			break;
		case 3:
			diff = "expert";
			break;
		}

		if (reportedScore == -1) {
			
			diff = ((RadioButton)v).getText().toString().trim().toLowerCase();
			if (diff.equalsIgnoreCase("easy")) stageSelect = 0;
			if (diff.equalsIgnoreCase("medium")) stageSelect = 1;
			if (diff.equalsIgnoreCase("hard")) stageSelect = 2;
			if (diff.equalsIgnoreCase("expert")) stageSelect = 3;
			populateScores(stageSelect);
		}
		else if (v == button1) {
		     try {
		         HttpClient client = new DefaultHttpClient();  
		         String postURL = "http://www.reedmagic.com/android/scorepost.php";
		         HttpPost post = new HttpPost(postURL); 
		             List<NameValuePair> params = new ArrayList<NameValuePair>();
		             params.add(new BasicNameValuePair("name", username.trim()));
		             params.add(new BasicNameValuePair("difficulty", diff));
		             params.add(new BasicNameValuePair("score", Integer.toString(reportedScore)));
		             UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
		             post.setEntity(ent);
		             HttpResponse responsePOST = client.execute(post);  
		             HttpEntity resEntity = responsePOST.getEntity();  
		             if (resEntity != null) {    
		                 button1.setEnabled(false);
		                 button1.setText("The world has been told.");
		                 //GO TO THE HOME SCREEN. DON'T STAY HERE. PLEASE.
		     			 Intent i = new Intent(ScoreScreen.this, YouMath.class);
		     			 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
		     			 i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		    			 startActivity(i);
		             }
		     } catch (Exception e) {
		         e.printStackTrace();
		     }
		}
	}
	catch(Exception e) {
		
	}
	}
	

	@Override
	public void onPause() {
		currentPos = SoundService.musicPlayer.getCurrentPosition();
		SoundService.currentPos = currentPos;
		SoundService.musicPlayer.pause();
		super.onPause();
	}
	
	@Override
	public void onResume() {
		SoundService.resumeAt();
		super.onResume();
	}
}

